﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Compilation;
using System.Web.Routing;
using System.Web.UI;

namespace WebFormRoutingHandler.Handler
{
    public class WebFormRouteHandler : IRouteHandler
    {
        public string VirtualPath { get; set; }

        public WebFormRouteHandler(string virtualPath)
        {
            VirtualPath = virtualPath;
        }

        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            foreach (KeyValuePair<string, object> token in requestContext.RouteData.Values)
            {
                requestContext.HttpContext.Items.Add(token.Key, token.Value);
            }
            foreach (KeyValuePair<string, object> token in requestContext.RouteData.DataTokens)
            {
                requestContext.HttpContext.Items.Add(token.Key, token.Value);
            }
            IHttpHandler result = BuildManager
                .CreateInstanceFromVirtualPath(VirtualPath, typeof(Page)) as IHttpHandler;
            return result;
        }
    }
}
